package com.example.blackmarket.module.Home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.viewpager.widget.ViewPager;

import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.blackmarket.R;
import com.example.blackmarket.adapter.LoopPagerAdapter;
import com.example.blackmarket.adapter.RecommendDataAdapter;
import com.example.blackmarket.entities.RecommendData;
import com.example.blackmarket.module.ErrandTask.DoRunning.DoRunningActivity;
import com.example.blackmarket.module.QuestionAnswer.Total.QuestionAnswerTotalActivity;
import com.example.blackmarket.module.SecondHandTrade.PostingSellOrWant.PostingSellOrWantActivity;
import com.example.blackmarket.module.SecondHandTrade.Shoplist.ShopListActivity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


public class HomeFragment extends Fragment implements MyViewPager.OnViewPagerTouchListener, ViewPager.OnPageChangeListener {

    private List<RecommendData> recommenddataList=new ArrayList<>();
    private View shopping_layout;
    private View running_layout;
    private View consultation_layout;
    
    private MyViewPager mLoopPager;
    private LoopPagerAdapter loopPagerAdapter;
    private static List<Integer> sPics=new ArrayList<>();
    private Handler mhandler;

    private LinearLayout pointContainer;
    //准备轮播图图片
    static {
        sPics.add(R.drawable.advertisement_1);
        sPics.add(R.drawable.advertisement_2);
        sPics.add(R.drawable.advertisement_3);
        sPics.add(R.drawable.advertisement_4);
    }

    //判断手指是否触摸
    private boolean mIsTouch=false;


    @Override
    public void onResume() {
        super.onResume();
        //当绑定窗口时
        mhandler.post(mLooperTask);
    }

    @Override
    public void onPause() {
        super.onPause();
        mhandler.removeCallbacks(mLooperTask);
    }



    private Runnable mLooperTask=new Runnable() {
        @Override
        public void run() {
            if(!mIsTouch){
            //切换viewpager里面的图片到下一个
            int currentItem=mLoopPager.getCurrentItem();
            mLoopPager.setCurrentItem(++currentItem,true);

            }
            mhandler.postDelayed(this,3000);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        Log.d("0", "onCreateView");
        View view= inflater.inflate(R.layout.fragment_home,container,false);
        return view;
    }
    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        Log.d("1", "onActivityCreated");
        super.onActivityCreated(savedInstanceState);

        //轮播图
        initView();
        //准备数据
        mhandler=new Handler();

        //模拟数据
        initData();
        RecyclerView recyclerView=(RecyclerView)getActivity().findViewById(R.id.recommend_data_recycler_view);
        StaggeredGridLayoutManager layoutManager=new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        RecommendDataAdapter adapter=new RecommendDataAdapter(recommenddataList);
        recyclerView.setAdapter(adapter);

        shopping_layout =  getActivity().findViewById(R.id.shopping_layout);
        shopping_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), ShopListActivity.class);
                startActivity(intent);
            }
        });

        running_layout = getActivity().findViewById(R.id.running_layout);
        running_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), DoRunningActivity.class);
                startActivity(intent);
            }
        });


        consultation_layout = getActivity().findViewById(R.id.consultation_layout);
        consultation_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), QuestionAnswerTotalActivity.class);
                startActivity(intent);
            }
        });
    }



    private void initData(){
        for(int i=0;i<10;i++){
            RecommendData data1=new RecommendData("宿舍楼有只猫皮皮，现在想为它求点猫粮",R.drawable.pipi1);
            recommenddataList.add(data1);
            RecommendData data2=new RecommendData("求猫粮！！看看星星吧，猫都要饿死了555",R.drawable.xingxing1);
            recommenddataList.add(data2);
            RecommendData data3=new RecommendData("闲置水杯，C5上门自取",R.drawable.shuibei1);
            recommenddataList.add(data3);
            RecommendData data4=new RecommendData("大四毕业了，出显示器一个",R.drawable.xianshiqi1);
            recommenddataList.add(data4);
            RecommendData data5=new RecommendData("额，出一本《小王子》",R.drawable.xiaowangzi1);
            recommenddataList.add(data5);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //这个方法的调用其实是viewpager停下来以后选中的位置
        int realPosition;
        if(loopPagerAdapter.getDataRealSize()!=0) {
            realPosition = position % loopPagerAdapter.getDataRealSize();
        }else{
            realPosition=0;
        }
        setSelectPoint(realPosition);
    }

    private void setSelectPoint(int realPosition) {
        for(int i=0;i<pointContainer.getChildCount();i++){
            View point=pointContainer.getChildAt(i);
            if(i!=realPosition){
                //那就是白色
                point.setBackgroundResource(R.drawable.shape_point_normal);
            }else{
                //选中的颜色
                point.setBackgroundResource(R.drawable.shape_point_selected);
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private void initView(){
        //找到viewPager控件
        mLoopPager=(MyViewPager)getActivity().findViewById(R.id.looper_pager);
        //设置适配器
        loopPagerAdapter=new LoopPagerAdapter();
        loopPagerAdapter.setData(sPics);
        mLoopPager.setAdapter(loopPagerAdapter);



        mLoopPager.setViewPagerTouchListener(this);
        mLoopPager.setOnPageChangeListener(this);
        //根据图片个数添加点的个数
        pointContainer=(LinearLayout)getActivity().findViewById(R.id.point_container);
        insertPoint();
        //因为设置了无限循环，因此从100轮开始，可以往回滑动，false代表不设置动画（不让用户察觉）
        mLoopPager.setCurrentItem(loopPagerAdapter.getDataRealSize()*100,false);

    }

    private void insertPoint() {
        for (int i=0; i<sPics.size();i++) {
            View point =new View(getActivity());
            LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(30,30);
            point.setBackground(getResources().getDrawable(R.drawable.shape_point_normal));
            layoutParams.leftMargin=20;
            point.setLayoutParams(layoutParams);
            pointContainer.addView(point);

        }
    }

    @Override
    public void onPagerTouch(boolean isTouch) {
        mIsTouch=isTouch;
    }




}
